package com.heima.gouzaofangfa;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//constructor构造方法赋值
public class ConstructDemo05 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Method1();
        Method02();
    }

    private static void Method02() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //获取类对象
        Class classnam = Class.forName("com.heima.gouzaofangfa.Student");
        //返回指定带参public的构造方法
        Constructor constructor = classnam.getConstructor(String.class, int.class);
        //创建反射对象，给参数赋值
        Object ke = constructor.newInstance("ke", 33);
        System.out.println(ke);
    }

    private static void Method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //获取类对象
        Class name = Class.forName("com.heima.gouzaofangfa.Student");
        //返回指定带参private的构造方法
        Constructor declaredConstructor = name.getDeclaredConstructor(String.class);
        //如果是非public的，需要临时取消检查，然后再创建对象
        declaredConstructor.setAccessible(true);
        //创建对象，并赋值
        Student student = (Student) declaredConstructor.newInstance("da");
        System.out.println(student);
    }
}
